<?php
namespace core;


class Config implements \ArrayAccess
{
    /**
     * @var Config
     */
    private static $instance;

    /**
     * @var array
     */
    public static $configs;

    public function __construct()
    {
    }

	static public function instance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new static();
        }
        return self::$instance;
    }

    static public function set($name, $value)
    {
        if (empty(self::$configs)) {
            self::$configs[$name] = $value;
        }
    }

    static public function get($name = '')
    {
        if ('' === $name) {
            return self::$configs;
        }

        if (strpos($name, '.')) {
            list($name, $key) = explode('.', $name);
            return self::$configs[$name][$key];
        }

        if (isset(self::$configs[$name])) {
            return self::$configs[$name];
        }
    }

    /**
     * 加载配置项
     * @author sweeterstar <2021/4/24>
     */
    static public function load()
    {
        // 获取所有配置项
        $files = glob(CONF_PATH . '*' . EXT);

        foreach ( $files as $file ) {
            $key = substr(strrchr($file, '/'), 1, -4);
            if (empty(self::$configs[$key])) {
                self::$configs[$key] = require $file;
            }
        }
    }

    /**
     * @param mixed $offset
     * @return bool
     * @author sweeterstar <2021/4/24>
     */
    public function offsetExists($offset)
    {
        return isset($this->configs[$offset]);
    }

    /**
     * @param mixed $offset
     * @return mixed
     * @author sweeterstar <2021/4/24>
     */
    public function offsetGet($offset)
    {
        if (isset($this->configs[$offset])) {
            $file = CONF_PATH . DS . $offset . EXT;
            $this->configs[$offset] = require $file;
        }
        return $this->configs[$offset];
    }

    /**
     * @param mixed $offset
     * @param mixed $value
     * @throws \Exception
     * @author sweeterstar <2021/4/25>
     */
    public function offsetSet($offset, $value)
    {
        // TODO: Implement offsetSet() method.
        throw new \Exception("cannot write config file.");
        
    }

    /**
     * @param mixed $offset
     * @author sweeterstar <2021/4/24>
     */
    public function offsetUnset($offset)
    {
        // TODO: Implement offsetUnset() method.
        unset($this->configs[$offset]);
    }
}